import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-22-括号生成
 * @date 2025/5/8 11:03
 */
public class Solution22 {

    // 每次都生成合法的括号
    // 有一种先扩充深度的感觉
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        dfs(ans, new StringBuilder(), 0, 0, n);
        return ans;
    }

    private void dfs(List<String> ans, StringBuilder s, int open, int close, int max) {
        if (s.length() == 2 * max) {
            ans.add(s.toString());
        }
        if (open < max) {
            s.append("(");
            dfs(ans, s, open + 1, close, max);
            s.deleteCharAt(s.length() - 1);
        }
        if (close < open) {
            s.append(")");
            dfs(ans, s, open, close + 1, max);
            s.deleteCharAt(s.length() - 1);
        }
    }
}
